﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

namespace SynoManager.FileStation.Tasks
{
    public class DownloadTask : TaskBase
    {
        private readonly IRemoteLocation[] filesAndFolders;
        private readonly string localPath;

        public DownloadTask(IRemoteLocation[] filesAndFolders, string localPath)
        {
            this.filesAndFolders = filesAndFolders;
            this.localPath = localPath;
        }

        public override void Execute()
        {
            Debug.WriteLine("Download " + Path.GetFileName(localPath), "DownloadTask");

            // create filename array
            List<string> files = new List<string>();
            foreach (IRemoteLocation file in filesAndFolders)
                files.Add(file.Name);

            // post data and get resultstream
            HttpWebResponse response = Queue.Service.client.Download(filesAndFolders[0].ParentPath, 
                Path.GetFileName(localPath), files.ToArray());

            Debug.WriteLine("Requesting file at File Station", "DownloadTask");

            Stream responseStream = response.GetResponseStream();
            FileMode access = FileMode.Create;
            FileStream fileStream = new FileStream(localPath, access);
            byte[] b = new byte[2048];
            while (true)
            {
                int n = responseStream.Read(b, 0, b.Length);
                if (n > 0)
                {
                    fileStream.Write(b, 0, n);
                    double progress = (float) fileStream.Length/(response.ContentLength);
                    Debug.WriteLine("Downloaded " +n+" bytes ("+((int)progress*100)+"%)", "DownloadTask");
                    OnProgressChanged(progress);
                }
                else
                    break;
            }
            responseStream.Close();
            fileStream.Close();

            Debug.WriteLine("Download complete", "DownloadTask");

            OnCompleted();
        }


        public override string DisplayTitle
        {
            get { return "Download " + Path.GetFileName(localPath); }
        }

        public override string DisplayDescription
        {
            get { return "Download " + filesAndFolders.Length + "file(s)/folder(s)"; }
        }

        public override System.Drawing.Image DisplayImage
        {
            get { return Properties.Resources.page_white_put; }
        }
    }
}
